<template>
  <div>
    <div class="children_content">
      <div class="children_content_flex">
        <div class="left_box">
          <organ-tree ref="organRef" @selected="treeSelected" />
        </div>
        <!-- <searchGroup v-model="searchObj" :options="searchOptions" @search="searchChange"
        @getHeight="setHeight" /> -->

        <div class="right_box">
          <div class="add_btns_box">
            <div class="box_left">
              <div class="title">分类</div>
            </div>
            <div class="box_right">
              <Space>
                <template v-if="currentTypeData && currentTypeData.id">
                  <Button type="primary" @click="editType">编辑分类</Button>
                  <Button type="error" @click="deleteType">删除分类</Button>
                  <Button type="primary" @click="handleEdit()">新建知识</Button>
                  <Button type="primary" @click="impExcelDisplay = true">导入</Button>
                </template>

                <Button type="primary" @click="expidsFile">导出</Button>
              </Space>
            </div>
          </div>

          <div class="content_table">
            <TemplateTable
              ref="templateTableRef"
              :data="tableData"
              :columns="tableColumns"
              :loading="loading"
              :height="tableHeight"
              :page="pageIndex"
              :page-size="pageSize"
              :total="total"
              checkbox
              border="none"
              size="small"
              stripe
              @page-change="handlePageChange"
            >
              <template #top="{ row }">
                <Icon v-if="row.top" type="md-checkmark" color="#0a0" />
              </template>
            </TemplateTable>
          </div>
        </div>
      </div>
    </div>

    <EditDialog
      ref="editDialogRef"
      v-if="showDialog"
      :currentTypeData="currentTypeData"
      :knowDetails="knowDetails"
      @cancel="handleDialogCancel"
      @submit="handleDialogSubmit"
    />

    <imp-excel-file
      v-if="impExcelDisplay"
      :currentTypeData="currentTypeData"
      @success="impExcelSuccess"
      @cancel="impExcelDisplay = false"
    />
  </div>
</template>
<script setup>
import { ref, onMounted, getCurrentInstance, inject, watch, nextTick, computed } from 'vue'
import { Message } from 'view-ui-plus'
import moment from 'moment'

import { faq } from '@/api/modules/knowledgeBase'
import { resolveBlob } from '@/util'

import OrganTree from './components/OrganTree.vue'
import EditDialog from './components/EditDialog.vue'
import ImpExcelFile from './components/ImpExcelFile.vue'
import TemplateTable from '@/components/TemplateTable/index.vue'
const props = defineProps({
  knowDetails: Object
})
// 屏幕高度
const screenHeight = inject('screenHeight')
// 搜索组件高度
const searchHeight = ref(null)
// 表格高度
const tableHeight = ref(0)
// 监听 screenHeight 的变化
watch(
  screenHeight,
  (newHeight) => {
    if (searchHeight.value) {
      tableHeight.value = newHeight - searchHeight.value - 290
    } else {
      tableHeight.value = newHeight - 290
    }
  },
  { immediate: true }
)

const templateTableRef = ref(null)

// 是否显示对话框
const showDialog = ref(false)
const editDialogRef = ref(null)

const impExcelDisplay = ref(false)
const impExcelRef = ref(null)

// 当前对象
const { proxy } = getCurrentInstance()

// 搜索条件字段
const searchObj = ref({
  name: '',
  type: '',
  dataSource: ''
})

const pageIndex = ref(1)
const pageSize = 20
const total = ref(0)

// 列表数据
const tableData = ref([])
const organRef = ref(null)

// 加载状态
const loading = ref(false)

// 表格列配置
const tableColumns = computed(() => [
  { title: '标题', field: 'title', type: 'link', minWidth: 280 },
  {
    title: '有效期开始',
    field: 'begintime',
    minWidth: 140,
    formatter: ({ cellValue }) => cellValue ? moment(cellValue).format('YYYY-MM-DD HH:mm:ss') : ''
  },
  {
    title: '有效期结束',
    field: 'endtime',
    minWidth: 140,
    formatter: ({ cellValue }) => cellValue ? moment(cellValue).format('YYYY-MM-DD HH:mm:ss') : ''
  },
  { title: '热门', field: 'top', slot: 'top', minWidth: 80 },
  { title: '创建人', field: 'orgi', minWidth: 140 },
  {
    title: '创建时间',
    field: 'createTime',
    minWidth: 140,
    formatter: ({ cellValue }) => moment(cellValue).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '更新时间',
    field: 'updateTime',
    minWidth: 140,
    formatter: ({ cellValue }) => moment(cellValue).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '操作',
    type: 'action',
    width: 140,
    fixed: 'right',
    actions: [
      {
        text: '编辑',
        onClick: (row) => handleEdit(row.id)
      },
      {
        text: '删除',
        type: 'del',
        onClick: (row) => handleDelete(row)
      }
    ]
  }
])

// 批量删除
const batchDel = () => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否批量删除选中数据?</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      Message.success('批量删除成功')
      getPageData(true)
    }
  })
}

const handleEdit = (id) => {
  showDialog.value = true
  nextTick(() => {
    editDialogRef.value.initDialog(id)
  })
}

const currentTypeData = ref(null)
const treeSelected = (data) => {
  currentTypeData.value = data
  getPageData(true)
}

const handleDelete = (row) => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否删除该数据?</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await faq.delete({
        data: {
          id: row.id
        }
      })
      Message.success('删除成功')
      getPageData(true)
    }
  })
}

const releaseSuccess = () => {
  releaseDialogDisplay.value = false

  getPageData()
}

// 处理对话框取消
const handleDialogCancel = () => {
  showDialog.value = false
}

// 处理对话框提交
const handleDialogSubmit = () => {
  showDialog.value = false
  // 刷新数据列表
  getPageData(true)
}

const impExcelSuccess = () => {
  impExcelDisplay.value = false
  getPageData()
}

const expidsFile = () => {
  const list = templateTableRef.value.getCheckboxRecords()

  if (!list.length) {
    return Message.warning('请选择需要导入的知识')
  }

  faq
    .expids({
      query: {
        ids: list.map((item) => item.id)
      }
    })
    .then((data) => {
      resolveBlob(data)
    })
}

// 获取数据源列表
const getPageData = (reset) => {
  if (reset) {
    pageIndex.value = 1
  }

  loading.value = true

  faq
    .page({
      query: {
        p: pageIndex.value,
        ps: pageSize
      },
      data: {
        cate: currentTypeData.value?.id || undefined
      }
    })
    .then(({ data }) => {
      tableData.value = data?.topicList || []
      total.value = data?.totalElements || 0
    })
    .finally(() => {
      loading.value = false
    })
}

// 处理页码变化
const handlePageChange = (page) => {
  pageIndex.value = page
  getPageData()
}

const editType = () => {
  organRef.value.handleCreateType(currentTypeData.value)
}

const deleteType = () => {
  organRef.value.handleDeleteType(currentTypeData.value.id)
}

// 获取组件高度
const setHeight = (height) => {
  searchHeight.value = height
  tableHeight.value = screenHeight.value - searchHeight.value - 245
}
</script>

<style lang="scss" scoped>
.left_box,
.children_content_flex,
.children_content {
  max-height: unset !important;
  height: unset !important;
}
</style>
